package io.github.xiaomak.gxsdxy_news;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ArrayList<String> mData = new ArrayList<String>();
    ListView mlistview;
    ArrayAdapter<String> mAdapter;
    AsyncTask Task;
    private SimpleAdapter simpleadapter;
    private List<Map<String,Object>>dataList = new ArrayList<Map<String,Object>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.setTitle("校园要闻");

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mlistview = (ListView) findViewById(R.id.listView);


        processData("http://gxsdxy.cn/catalog-list/96/1");

        simpleadapter=new SimpleAdapter(this,dataList,R.layout.item,new String[]{"title","time"},new int[]{R.id.contitle,R.id.contime});

//        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mData);
//        mlistview.setAdapter(mAdapter);
        mlistview.setAdapter(simpleadapter);

        mlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView listView = (ListView)parent;
                @SuppressWarnings("unchecked")
                HashMap<String, Object> map = (HashMap<String, Object>)listView.getItemAtPosition(position);
//                String url = map.get("url").toString();
//                String title = map.get("title").toString();
                Intent data = new Intent(MainActivity.this,NewActivity.class);
                data.putExtra("url", map.get("url").toString());
                data.putExtra("title",map.get("title").toString());
                setResult(1, data);
                startActivity(data);


            }
        });

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.action_exit) {
            System.exit(0);
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.school_news) {
            // Handle the camera action

            Task.cancel(true);//如果Task还在运行，则先取消它
            Task = null;

            dataList.clear();

            this.setTitle("校园要闻");

            processData("http://gxsdxy.cn/catalog-list/96/1");


            simpleadapter=new SimpleAdapter(this,dataList,R.layout.item,new String[]{"title","time"},new int[]{R.id.contitle,R.id.contime});


            mlistview.setAdapter(simpleadapter);

        } else if (id == R.id.school_inform) {

            Task.cancel(true);//如果Task还在运行，则先取消它
            Task = null;

            dataList.clear();

            this.setTitle("校园通知");

            processData("http://gxsdxy.cn/catalog-list/96/2");
            simpleadapter=new SimpleAdapter(this,dataList,R.layout.item,new String[]{"title","time"},new int[]{R.id.contitle,R.id.contime});


            mlistview.setAdapter(simpleadapter);

        } else if (id == R.id.school_notice) {

            Task.cancel(true);//如果Task还在运行，则先取消它
            Task = null;

            dataList.clear();

            this.setTitle("公示公告");

            processData("http://gxsdxy.cn/catalog-list/96/3");

            simpleadapter=new SimpleAdapter(this,dataList,R.layout.item,new String[]{"title","time"},new int[]{R.id.contitle,R.id.contime});


            mlistview.setAdapter(simpleadapter);


        } else if (id == R.id.society_hot) {

            Task.cancel(true);//如果Task还在运行，则先取消它
            Task = null;

            dataList.clear();

            this.setTitle("社会热点");

            processData("http://gxsdxy.cn/catalog-list/96/24");

            simpleadapter=new SimpleAdapter(this,dataList,R.layout.item,new String[]{"title","time"},new int[]{R.id.contitle,R.id.contime});


            mlistview.setAdapter(simpleadapter);

        } else if (id == R.id.department_news) {

            Task.cancel(true);//如果Task还在运行，则先取消它
            Task = null;

            dataList.clear();

            this.setTitle("系部动态");

            processData("http://gxsdxy.cn/catalog-list/96/113");

            simpleadapter=new SimpleAdapter(this,dataList,R.layout.item,new String[]{"title","time"},new int[]{R.id.contitle,R.id.contime});


            mlistview.setAdapter(simpleadapter);


        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_setting) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }



    private void processData(final String url){
        Task = new AsyncTask<String,Void,ArrayList<Map<String,Object>>>(){

            @Override
            protected void onPostExecute(ArrayList<Map<String, Object>> maps) {
                super.onPostExecute(maps);
                simpleadapter.notifyDataSetChanged();
            }

            @Override
            protected ArrayList<Map<String, Object>> doInBackground(String... params) {
                String URL = params[0];
                String ur = null;
                String title = null;
                String time = null;
                try {
                    Document doc = Jsoup.connect(URL).get();
                    Elements link = doc.select(".views-table tbody tr");
                    for (Element e : link) {
                        Elements vft= e.select(".views-field-title a");
                        for (Element data : vft){
                            ur = data.attr("href");

                                title = subString(data.text(),16,"...");
                        }
                        Elements date= e.select(".date-display-single");
                        for (Element data : date){
                            time = data.text();
                        }
                        Map<String,Object>map=new HashMap<String, Object>();
                        map.put("url",ur);
                        map.put("title",title);
                        map.put("time",time);
                        dataList.add(map);
                    }



                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return null;
            }
        }.execute(url);
    }

    public static String subString(String text, int length, String endWith) {
        int textLength = text.length();
        int byteLength = 0;
        StringBuffer returnStr =  new StringBuffer();
        for(int i = 0; i<textLength && byteLength < length*2; i++){
            String str_i = text.substring(i, i+1);
            if(str_i.getBytes().length == 1){//英文
                byteLength++;
            }else{//中文
                byteLength += 2 ;
            }
            returnStr.append(str_i);
        }
        try {
            if(byteLength<text.getBytes("GBK").length){//getBytes("GBK")每个汉字长2，getBytes("UTF-8")每个汉字长度为3
                returnStr.append(endWith);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnStr.toString();
    }


}
